﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;


namespace MeetingManagerLib
{
    /// <summary>
    /// 对数据库的表进行读写操作
    /// </summary>
    public class TableCommand
    {
        /// <summary>类在运行时是否产生错误或异常</summary>
        /// <value>，IsError为true代表产生了异常，否则运行正常.</value>
        public bool IsError = false;

        /// <summary>
        /// 当IsError为true时，此属性表示出错的详细原因.
        /// </summary>
        public string ErrorMessage = "";
        public TableCommand()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 从数据库的表中读取指定字段的值
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl] WHERE [id] = 6"</param>
        /// <param name="strField">指定字段的名称。如:"user"</param>
        /// <returns>指定字段的值；如果执行SQL语句后没有查到记录或多于一条记录都返回""字符串；如在处理中产生错误或异常，则设置IsError为true,同时在ErrorMessage属性中给出错误信息。</returns>
        public string ReadTableFieldValue(string strSQL, string strField)
        {
            string strReturn = "";
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                if (ds.Tables[0].Rows.Count == 1)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    strReturn = row[strField].ToString();
                }
                else
                {
                    IsError = true;
                    ErrorMessage = "执行完SQL语句[" + strSQL + "]后，表中记录有[" + ds.Tables[0].Rows.Count.ToString() + "]条，不知从那条记录读出指定字段的值！";
                }

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[private string ReadTableFieldValue(string strSQL,string strField)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
            return strReturn;
        }

        /// <summary>
        /// 向数据库的表中写入指定字段值
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl] WHERE [id] = 6"</param>
        /// <param name="strField">指定字段的名称。如:"user"</param>
        /// <param name="strValue">指定字段的值。如:"张三"</param>
        /// <returns>无。请从IsError属性检测是否出错</returns>
        public void WriteTableFieldValue(string strSQL, string strField, string strValue)
        {
            IsError = false;
            ErrorMessage = "";

            DataSet ds = new DataSet();
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                if (ds.Tables[0].Rows.Count == 1)
                {
                    ds.Tables[0].Rows[0][strField] = strValue;
                }
                else
                {
                    IsError = true;
                    ErrorMessage = "执行完SQL语句[" + strSQL + "]后，表中记录有[" + ds.Tables[0].Rows.Count.ToString() + "]条，不知向那条记录写入指定字段的值！";
                }

                oda.UpdateCommand = dbcb1.GetUpdateCommand();
                oda.Update(ds.Tables[0]);

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();
            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[private void WriteTableFieldValue(string strSQL, string strField,string strValue)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
        }

        /// <summary>
        /// 查询数据库的表中符合SQL语句条件的记录个数
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl] WHERE [id] = 6"</param>
        /// <returns>查询到的记录数</returns>
        public int QueryTableRows(string strSQL)
        {
            int intReturn = 0;
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                intReturn = ds.Tables[0].Rows.Count;

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[public int QueryTableRows(string strSQL)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
            return intReturn;
        }

        /// <summary>
        /// 从数据库的表中读取符合条件的记录的字段的值
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl] WHERE [id] = 6"</param>
        /// <param name="strField">指定字段的名称。如:"user"</param>
        /// <returns>无返回。读取的值通过参数数组传回</returns>
        public void ReadTableRowsFieldValue(string strSQL,string[,] arry,params string[] strFields)
        {
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                if (ds.Tables[0].Rows.Count != 0)
                {
                    DataRow row;
                    for( int i=0; i < ds.Tables[0].Rows.Count; i++ )
                    {
                        row = ds.Tables[0].Rows[i];
                        for (int t = 0; t < strFields.Length; t++)
                        {
                            arry[i,t] = row[strFields[t]].ToString();
                        }
                    }
                }
                else
                {
                    IsError = true;
                    ErrorMessage = "执行完SQL语句[" + strSQL + "]后，表中没有查询到记录，无法读出指定字段的值！";
                }

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[public string ReadTableRowsFieldValue(string strSQL, string strField,string[] arry)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
        }
        /// <summary>
        /// 向数据库的表中写入符合条件的记录的字段的值
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl] WHERE [id] = 6"</param>
        /// <param name="strField">指定字段的名称。如:"user"</param>
        /// <returns>无返回。读取的值通过参数数组传回</returns>
        public void WriteTableRowsFieldValue(string strSQL,string[,] arry,params string[] strFields)
        {
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                if (ds.Tables[0].Rows.Count != 0)
                {
                    DataRow row;
                    for( int i=0; i < ds.Tables[0].Rows.Count; i++ )
                    {
                        row = ds.Tables[0].Rows[i];
                        for (int t = 0; t < strFields.Length; t++)
                        {
                            row[strFields[t]] = arry[i,t];
                        }
                    }
                    oda.UpdateCommand = dbcb1.GetUpdateCommand();
                    oda.Update(ds.Tables[0]);
                }
                else
                {
                    IsError = true;
                    ErrorMessage = "执行完SQL语句[" + strSQL + "]后，表中没有查询到记录，无法读出指定字段的值！";
                }

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[public string ReadTableRowsFieldValue(string strSQL, string strField,string[] arry)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
        }
        /// <summary>
        /// 向数据库的表中插入多条记录和相应字段的值
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl]"，注意不能要 WHERE [id] = 6字句</param>
        /// <param name="strField">指定字段的名称。如:"user"</param>
        /// <returns>无返回。读取的值通过参数数组传回</returns>
        public void InsertTableRowsFieldValue(string strSQL, int iRows,string[,] arry, params string[] strFields)
        {
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                for (int i = 0; i < iRows; i++)
                {
                    DataRow row = ds.Tables[0].NewRow();
                    for (int t = 0; t < strFields.Length; t++)
                    {
                        row[strFields[t]] = arry[i, t];
                    }
                    ds.Tables[0].Rows.Add(row);
                }
                oda.UpdateCommand = dbcb1.GetUpdateCommand();
                oda.Update(ds.Tables[0]);

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[public string ReadTableRowsFieldValue(string strSQL, string strField,string[] arry)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
        }

        /// <summary>
        /// 删除数据库表中多条记录
        /// </summary>
        /// <param name="strSQL">查询表的完整SQL语句。如:"SELECT * FROM [hyjl]"，注意不能要 WHERE [id] = 6字句</param>
        /// <returns>无返回。读取的值通过参数数组传回</returns>
        public void DeleteTableRows(string strSQL)
        {
            DataSet ds = new DataSet();

            IsError = false;
            ErrorMessage = "";
            try
            {
                System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings["permitConnectionString"];
                SqlConnection sqlcon = new SqlConnection(s.ConnectionString);
                SqlDataAdapter oda = new SqlDataAdapter(strSQL, sqlcon);
                SqlCommandBuilder dbcb1 = new SqlCommandBuilder(oda);

                oda.Fill(ds);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i].Delete();
                }
                oda.UpdateCommand = dbcb1.GetUpdateCommand();
                oda.Update(ds.Tables[0]);

                oda.Dispose();
                sqlcon.Dispose();
                ds.Dispose();

            }
            catch (Exception s)
            {
                IsError = true;
                ErrorMessage = "错误位置：文件 MeetingManagerLib.cs 中的class TableCommand 中的方法[public void DeleteTableRows(string strSQL)]";
                ErrorMessage += "错误信息：";
                ErrorMessage += s.Message;
            }
        }
    }


    /// <summary>
    /// 检测数据内容的类型
    /// </summary>
    public class DataTypeCheck
    {
        /// <summary>
        /// 检测字符串中是否只有数字和大小写字母的组合
        /// </summary>
        /// <param name="strSource">要检测的字符串</param>
        /// <returns>如果只有数字和大小写字母的组合，返回true，否则返回false</returns>
        public static bool IsDigitOrLetter( string strSource )
        {

            if (System.Text.RegularExpressions.Regex.IsMatch(strSource, @"(?i)^[0-9a-zA-Z]+$"))
                return true;
            else 
                return false;
        }
        /// <summary>
        /// 检测字符串中是否只有数字
        /// </summary>
        /// <param name="strSource">要检测的字符串</param>
        /// <returns>如果只有数字，返回true，否则返回false</returns>
        public static bool IsDigit(string strSource)
        {

            if (System.Text.RegularExpressions.Regex.IsMatch(strSource, @"^\d*(?:$|\.\d*$)"))
                return true;
            else
                return false;
        }
        /// <summary>   
        /// 判断日期的全部格式   
        /// </summary>   
        /// <param name="dateStr">输入日期的字符串</param>   
        /// <returns></returns>   
        public static bool IsDate(string dateStr)
        {
            bool _isDate = false;

            string matchStr = "";

            matchStr += @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) ";
            matchStr += @"(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$ ";

            System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions.IgnoreCase | (System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace));

            if (System.Text.RegularExpressions.Regex.IsMatch(dateStr, matchStr, option))
                _isDate = true;
            else
                _isDate = false;

            return _isDate;
        }
    }

    /// <summary>
    /// 对用户密码进行的操作
    /// </summary>
    public class Password
    {
        public static string PasswordEncryption(string strPwd)
        {

            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strPwd, "MD5"); ;
        }
    }

    /// <summary>
    /// 对数据类型进行的格式化显示
    /// </summary>
    public class FormatDataDisplayStyle
    {

        public static string DateTimeToDate_YYY_MM_DD(DateTime d)
        {
            return d.ToString("yyyy'-'MM'-'dd", System.Globalization.CultureInfo.CreateSpecificCulture("zh-CN"));
        }


        /// <summary>
        /// 从字母、汉字混合的字符串中截取指定字节长度的字符串，且不会截断汉字（遇到半个汉字截断时，回退一个字节，即少返回一个字节的串
        /// </summary>
        /// <param name="source">字母、汉字混合的字符串</param>
        /// <param name="len">截取字符串的长度。注：一个汉字长度算2，一个英文字符长度算1</param>
        /// <returns>截取后的字符串</returns>
        public static string SubUnicodTextLenByte(string source, int len)
        {
            int i = 0;
            int off = 0;

            byte[] temp = System.Text.Encoding.Default.GetBytes(source);
            if (temp.Length < len)
                len = temp.Length;
            while (i < len)
            {
                if (temp[i] > 128)
                {
                    i += 2;
                    off++;
                }
                else
                {
                    i++;
                    off++;
                }
            }
            if (i > len)
                off--;

            return source.Substring(0, off);
        }
    }

    public class PopWebFrom
    {
        public void AddReturnValueScript(System.Web.UI.Page page)
        {
            string strKey = "ChooseName";

            Type cstype = page.GetType();
            System.Web.UI.ClientScriptManager cs = page.ClientScript;
            if (!cs.IsClientScriptBlockRegistered(cstype, strKey))
            {
                System.Text.StringBuilder strScript = new System.Text.StringBuilder();

                strScript.Append("<script type='text/javascript'>");
                //strScript.Append("//<!--");
                strScript.Append("    function closeWin(strReturn,id) ");
                strScript.Append("    {");
                strScript.Append("        window.returnValue = strReturn;");
                strScript.Append("        window.opener.document.forms[0].elements[id].value = strReturn;");
                strScript.Append("        window.opener.document.forms[0].submit();");
                strScript.Append("        window.close();");
                strScript.Append("    }   ");
                //strScript.Append("//-->");
                strScript.Append("</script>");

                cs.RegisterClientScriptBlock(cstype, strKey, strScript.ToString(), false);

            }
        }

        public void OpenPopUp(System.Web.UI.WebControls.WebControl opener, string PagePath, string WebControlClientID, string windowName, int width, int height)
        {
            string clientScript;
            string windowAttribs;

            //Building Client side window attributes with width and height.
            //Also the the window will be positioned to the middle of the screen
            windowAttribs = "menubar =no,width=" + width + "px," + "height=" + height + "px," + "left='+((screen.width -" + width + ") / 2)+'," + "top='+( (screen.height - " + height + ") / 2 ) +'";

            //Building the client script - window.open, with additional parameters
            clientScript = "javascript:window.open('" + PagePath + "?WebControlClientID=" + WebControlClientID + "&WebControlText=' + window.document.forms[0].elements['" + WebControlClientID + "'].value ,'" + windowName + "','" + windowAttribs + "');return false;";
            //register the script to the clientside click event of 'opener' control
            opener.Attributes.Add("onClick", clientScript);
        }
    }

    public class PopWebFromReturnTwoVal
    {
        public void AddReturnValueScript(System.Web.UI.Page page, string strKey)
        {

            Type cstype = page.GetType();
            System.Web.UI.ClientScriptManager cs = page.ClientScript;
            if (!cs.IsClientScriptBlockRegistered(cstype, strKey))
            {
                System.Text.StringBuilder strScript = new System.Text.StringBuilder();

                strScript.Append("<script type='text/javascript'>");
                //strScript.Append("//<!--");
                strScript.Append("    function closeWin(strReturn1,strReturn2,elemID1,elemID2) ");
                strScript.Append("    {");
                strScript.Append("        window.returnValue = strReturn1;");
                strScript.Append("        window.opener.document.forms[0].elements[elemID1].value = strReturn1;");
                strScript.Append("        window.opener.document.forms[0].elements[elemID2].value = strReturn2;");
                strScript.Append("        window.opener.document.forms[0].submit();");
                strScript.Append("        window.close();");
                strScript.Append("    }   ");
                //strScript.Append("//-->");
                strScript.Append("</script>");

                cs.RegisterClientScriptBlock(cstype, strKey, strScript.ToString(), false);

            }
        }

        public void OpenPopUp(System.Web.UI.WebControls.WebControl opener, string PagePath,string WebControlClientID1, string WebControlClientID2, string windowName, int width, int height)
        {
            string clientScript="";
            string windowAttribs;

            //Building Client side window attributes with width and height.
            //Also the the window will be positioned to the middle of the screen
            windowAttribs = "width=" + width + "px," + "height=" + height + "px," + "left='+((screen.width -" + width + ") / 2)+'," + "top='+( (screen.height - " + height + ") / 2 ) +'";

            //Building the client script - window.open, with additional parameters
            clientScript += "javascript:window.open('" + PagePath;
            clientScript += "?WebControlClientID1=" + WebControlClientID1 + "&WebControlText1=' + window.document.forms[0].elements['" + WebControlClientID1 + "'].value";
            clientScript += "+'&WebControlClientID2=" + WebControlClientID2 + "&WebControlText2=' + window.document.forms[0].elements['" + WebControlClientID2 + "'].value";
            clientScript +=" ,'" + windowName + "','" + windowAttribs + "');return false;";
            //register the script to the clientside click event of 'opener' control
            opener.Attributes.Add("onClick", clientScript);
        }

        public void AddButtonClickScript(System.Web.UI.WebControls.Button btnOk, string strReturn1, string strReturn2, string WebControlClientID1, string WebControlClientID2)
        {
            string strJS = "";
            strJS += "javascript:closeWin(";
            strJS += "'" + strReturn1 + "'";
            strJS += ",";
            strJS += "'" + strReturn2 + "'";
            strJS += ",";
            strJS += "'" + WebControlClientID1 + "'";
            strJS += ",";
            strJS += "'" + WebControlClientID2 + "'";
            strJS += ")";
            btnOk.Attributes.Add("onclick", strJS);
        }
    }

    public class FillWebControl
    {

        public bool FillListControl(System.Web.UI.WebControls.DropDownList ctl, string strSQL, params string[] strFields)
        {
            TableCommand table = new TableCommand();
            int iRows = table.QueryTableRows(strSQL);
            if (!table.IsError)
            {
                string[,] arry = new string[iRows, 2];
                table.ReadTableRowsFieldValue(strSQL, arry, strFields);
                if (!table.IsError)
                {
                    for (int i = 0; i < iRows; i++)
                    {
                        System.Web.UI.WebControls.ListItem lt = new System.Web.UI.WebControls.ListItem(arry[i, 0], arry[i, 1]);
                        ctl.Items.Add(lt);
                    }
                    return true;
                }
            }
            return false;
        }

    }

    public class QuanXian
    {
        public void Check(System.Web.UI.Page page, string strQxID)
        {
            if (page.Session["UserQx"] == null)
            {
                page.Response.Redirect("/public_page/Error_Relogin.aspx?Title=网络会话失效&Info1=您长时间没有使用本页面，与服务器间的连接失效！&Info2=请您重新登陆软件。");
                return;
            }
            else  //管理员权限
            {
                System.Text.RegularExpressions.Match n = System.Text.RegularExpressions.Regex.Match(page.Session["UserQx"].ToString(), "~0,");
                if (n.Success) 
                    return;
            }
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(page.Session["UserQx"].ToString(), "~" + strQxID + ",");
            if (!m.Success)
            {
                TableCommand table = new TableCommand();
                string strQxName = table.ReadTableFieldValue("SELECT * FROM [quanxian_name] WHERE [id] = " + strQxID, "name");
                page.Response.Redirect("/public_page/Error.aspx?Title=权限不足&Info1=对不起，您没有使用" + strQxName + "功能的权限！&Info2=您可以向公司办公室或系统管理员申请使用该项功能。");
            }
        }

        public bool Test(System.Web.UI.Page page, string strQxID)
        {
            if (page.Session["UserQx"] == null)
            {
                page.Response.Redirect("/public_page/Error_Relogin.aspx?Title=网络会话失效&Info1=您长时间没有使用本页面，与服务器间的连接失效！&Info2=请您重新登陆软件。");
                return false;
            }
            else //管理员权限
            {
                System.Text.RegularExpressions.Match n = System.Text.RegularExpressions.Regex.Match(page.Session["UserQx"].ToString(), "~0,");
                if (n.Success)  
                    return true;
            }
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(page.Session["UserQx"].ToString(), "~" + strQxID + ",");
            return m.Success;
        }
    }
}